package com.crawl.proxy.task;

import com.crawl.core.util.Config;
import com.crawl.core.util.HttpClientUtil;
import com.crawl.proxy.ProxyPool;
import com.crawl.proxy.entity.Proxy;
import com.crawl.zhihu.ZhiHuHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 代理序列化task
 */
public class ProxySerializeTask implements Runnable{
    private static Logger logger = LoggerFactory.getLogger(ProxySerializeTask.class);

    /**
     * 实现Runnable接口方法
     * 每隔1分钟序列化当前可用代理至文件
     */
    @Override
    public void run() {
        while (!ZhiHuHttpClient.isStop){
            try {
                Thread.sleep(1000 * 60 * 1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Proxy[] proxyArray = null;
            //ProxyPool中可用的代理，添加至proxyArray
            proxyArray = ProxyPool.proxyQueue.toArray(new Proxy[0]);
            //序列化代理至硬盘
            HttpClientUtil.serializeObject(proxyArray, Config.proxyPath);
            logger.info("成功序列化" + proxyArray.length + "个代理");
        }
    }
}
